import router from "./router";
import store from "./store";
import { Message } from "element-ui";
import NProgress from "nprogress"; // progress bar
import "nprogress/nprogress.css"; // progress bar style
import { getToken } from "@/utils/auth"; // get token from cookie
import getPageTitle from "@/utils/get-page-title";

NProgress.configure({ showSpinner: false }); // NProgress Configuration

const whiteList = ["/login"]; // no redirect whitelist

router.beforeEach(async (to, from, next) => {
  // start progress bar
  NProgress.start();

  // set page title
  document.title = getPageTitle(to.meta.title);
  const hasToken = getToken("token");
  const hasUserId = getToken("userId");
  const hasAccount = getToken("userInfo");
  // const hasAccount = store.state.user.userInfo.account.length;
  if (hasToken && hasUserId && hasAccount) {
    if (to.path === "/login") {
      // if is logged in, redirect 选择基地页
      next({ path: "/" });
      NProgress.done();
    } else {
      // 可以判断是否更改过用户信息 比如更改该用户的权限路由
      const userStatus = store.getters.status;
      if (userStatus) {
        next();
      } else {
        try {
          store.commit("user/SET_STATUS", true);
          // console.log("请求路由");
          // 请求路由
          const accessRoutes = await store.dispatch(
            "permission/generateRoutes"
          );
          // router.addRoutes(accessRoutes);
          const accessScRoutes = await store.dispatch(
            "permission/geneSyRateRoutes"
          );
          // router.addRoutes(accessRoutes);
          const accessAdminRoutes = await store.dispatch(
            "permission/geneAdminRateRoutes"
          );
          // router.addRoutes(accessRoutes);
          const asyncMonitorRoutes = await store.dispatch(
            "permission/geneMonitorRateRoutes"
          );
          // router.addRoutes(accessRoutes);
          const asyncSocialRoutes = await store.dispatch(
            "permission/geneSocialRateRoutes"
          );
          // router.addRoutes(accessRoutes);
          const asyncAgriculturalSocialRoutes = await store.dispatch(
            "permission/geneAgriculturalSocialRateRoutes"
          );
          router.addRoutes(accessRoutes);
          router.addRoutes(accessScRoutes);
          router.addRoutes(accessAdminRoutes);
          router.addRoutes(asyncMonitorRoutes);
          router.addRoutes(asyncSocialRoutes);
          router.addRoutes(asyncAgriculturalSocialRoutes);
          next({ ...to, replace: true });
          // 路由完成加载后如果检测到没有基地ID 则跳转到选择公司页面
          // const hasBaseId = getToken("organizationId");
          // if (!hasBaseId) {
          //   if (to.path !== "/choose-company") {
          //     Message.error("检测到基地身份信息过期，请重新选择基地");
          //   }
          //   next({ path: "/" });
          // }
        } catch (error) {
          await store.dispatch("user/resetToken");
          Message.error(error || "Has Error");
          next(`/login?redirect=${to.path}`);
          NProgress.done();
        }
      }
    }
  } else {
    /* has no token*/
    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next();
    } else {
      Message.error("登录已过期,请重新登录");
      // other pages that do not have permission to access are redirected to the login page.
      // next(`/login?redirect=${to.path}`);
      next(`/login`);
      NProgress.done();
    }
  }
});

router.afterEach(() => {
  // finish progress bar
  NProgress.done();
});
